package controller.group_management;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.group_management.GroupManagementAdapter;
import define.API;
import define.Key;
import model.group_management.GroupManagementItem;
import ui.fragment.group_management.GroupManagementFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class GroupManagementAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private long added_time = 0;
    private int number_of_users = 0;
    private String USER_PENDING_LIST = "";
    private String USER_NATIVE_IDS = "";
    private String PENDING_USER_NATIVE_IDS = "";
    private String USER_STATUS = "";
    private String USER_ROLE = "";
    private int number_of_shots = 0;
    private long group_id = 0;
    private String GROUP_NAME = "" ;
    private String GROUP_DESCRIPTION = "";

    private String ERROR = "";
    private String STATUS = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <GroupManagementItem> mAlGroupManagement = new ArrayList<>();
    public static ArrayList <Long> mAlGroupId = new ArrayList<>();

    public GroupManagementAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            GroupManagementFragment.groupManagementAdapter = new GroupManagementAdapter(mContext,
                    R.layout.simple_grid_item_group_management, mAlGroupManagement);
            GroupManagementFragment.mGvInGroupManagementFragment.setAdapter(GroupManagementFragment.groupManagementAdapter);
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_GROUP_LIST_BY_COMPANY);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.COMPANY_ID_GROUP, params[3]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", GroupManagementAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get mJaGroups in mJoXml
                JSONArray mJaGroups = mJoXml.getJSONArray(Key.GROUPS);
                if (!"[]".equals(mJaGroups.toString())) {
                    //get mJoGroups from mJaGroups
                    for (int i = 0; i < mJaGroups.length(); i++) {
                        JSONObject mJoGroups = mJaGroups.getJSONObject(i);
                        //get string from mJoGroups
                        added_time = mJoGroups.getLong(Key.ADDED_TIME);
                        number_of_users = mJoGroups.getInt(Key.NUMBER_OF_USERS);
//                        USER_PENDING_LIST = mJoGroups.getString(Key.USER_PENDING_LIST);
//                        USER_NATIVE_IDS = mJoGroups.getString(Key.USER_NATIVE_IDS);
//                        PENDING_USER_NATIVE_IDS = mJoGroups.getString(Key.PENDING_USER_NATIVE_IDS);
//                        USER_STATUS = mJoGroups.getString(Key.USER_STATUS);
//                        USER_ROLE = mJoGroups.getString(Key.USER_ROLE);
                        number_of_shots = mJoGroups.getInt(Key.NUMBER_OF_SHOTS);
                        group_id = mJoGroups.getLong(Key.GROUP_ID);
                        GROUP_NAME = mJoGroups.getString(Key.GROUP_NAME);
                        GROUP_DESCRIPTION = mJoGroups.getString(Key.GROUP_DESCRIPTION);
                        ArrayList <Long> mAlGroupUserIdsItem = new ArrayList<>();
                        //get mJaGroupUserIds from mJoGroups
                        JSONArray mJaGroupUserIds = mJoGroups.getJSONArray(Key.GROUP_USER_IDS);
                        //get mJoGroupUsersIds from mJaGroupUserIds
                        if (!"[]".equals(mJaGroupUserIds.toString())) {
                            for (int m = 0; m < mJaGroupUserIds.length(); m++) {
                                mAlGroupUserIdsItem.add(mJaGroupUserIds.getLong(m));
                            }
                        }
                        ArrayList<String> mAlGroupUserNamesItem = new ArrayList<>();
                        //get mJaGroupUserNames from mJoGroups
                        JSONArray mJaGroupUserNames = mJoGroups.getJSONArray(Key.GROUP_USER_NAMES);
                        //get mJoGroupUserName from mJaGroupUserName
                        if (!"[]".equals(mJaGroupUserNames.toString())) {
                            for (int n = 0; n < mJaGroupUserNames.length(); n++) {
                                mAlGroupUserNamesItem.add(mJaGroupUserNames.getString(n));
                            }
                        }
                        GroupManagementItem groupManagementItem = new GroupManagementItem(
                                added_time, number_of_users, USER_PENDING_LIST,
                                USER_NATIVE_IDS, PENDING_USER_NATIVE_IDS, USER_STATUS,
                                USER_ROLE, number_of_shots, group_id,
                                GROUP_NAME, GROUP_DESCRIPTION, mAlGroupUserIdsItem,
                                mAlGroupUserNamesItem
                        );
                        if (!mAlGroupId.contains(group_id)) {
                            mAlGroupManagement.add(groupManagementItem);
                            mAlGroupId.add(group_id);
                        }
                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}